#include "HttpServer.hpp"
#include <memory>

using namespace std;
using namespace server;

void Usage(std::string proc)
{
    cerr << "Usage: \n\t" << proc << "proc\r\n\r\n";
}
std::string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
    {
        ct += "application/x-jpg";
    }
    ct += "\r\n";
    return ct;
}
// 1. 服务器和网页分离，html
// 2. url -> / : web根目录
// 3. 我们要正确的给客户端返回资源类型，我们首先要自己知道！！！ 所有的资源都有后缀！！！
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    cout << "------------------- http start ------------------------------" << endl;
    cout << req.inbuffer << endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpversion: " << req.httpversion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    cout << "------------------- http end ------------------------------" << endl;

    std::string respline = "HTTP/1.1 200 OK \r\n"; // 状态行
    // std::string respline = "HTTP/1.1 307 Temporary Redirect \r\n"; // 状态行
    std::string respheader = suffixToDesc(req.suffix); // 响应报头
    if (req.size > 0)
    {
        respheader += "Content-Length: ";
        respheader += std::to_string(req.size);
        respheader += "\r\n"; // 空行
    }

    respheader += "Set-Cookie: 123456abcdfg\r\n"; //Cookie
    // 以后，每次http请求，都会自动携带曾经所设置的所有的cookie，帮服务器进行鉴权行为 ---- http会话保持

    // respheader += "Location: https://tongyi.aliyun.com/\r\n"; // 重定向搭配状态码307还有几个
    std::string respblank = "\r\n"; // 空行
    // std::string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>Hello World</h1></head><body><p>每个进程都有自己的独立资源，因此需要注意资源的管理和释放。</p></body></html>";
    std::string body; // 这是响应正文
    body.resize(req.size + 1);
    if (!Util::readFile(req.path, (char *)body.c_str(), req.size))
    {
        Util::readFile(html_404, (char *)body.c_str(), req.size); // 这里一能成功
    }
    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;

    cout << "--------------------- http  response start---------------------------------" << endl;
    std::cout << resp.outbuffer << std::endl;
    cout << "--------------------- http  response end---------------------------------" << endl;
    resp.outbuffer += body;

    return true;
}

// ./httpserver 8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<HttpServer> httpsvr(new HttpServer(Get, port));
    // httpsvr->registerCb("/", Get); // http的功能路由
    // httpsvr->registerCb("/search", Search);
    // httpsvr->registerCb("/test.py", Other);
    httpsvr->initServer();
    httpsvr->start();
}